import { defineStore } from "pinia";
import { ref } from "vue";
import { FaultReportAPI, FaultReportItem } from "@/api/hmi/fault-report.api";
import { store } from "@/store";

/**
 * 故障报告 Store
 */
export const useFaultReportStore = defineStore("faultReport", () => {
  // 状态
  const loading = ref(false);
  const faultReportList = ref<FaultReportItem[]>([]);
  const total = ref(0);
  const selectedIds = ref<number[]>([]);
  const faultReport = ref<FaultReportItem[]>([]);

  /**
   * 获取新故障报告详情
   * @param cpuId 故障报告ID
   * @returns Promise<NewFaultReportItem>
   */
  async function fetchFaultReportByCpuId(cpuId: string | number): Promise<FaultReportItem[]> {
    return new Promise((resolve, reject) => {
      FaultReportAPI.getFaultReportByCpuId(cpuId)
        .then((res) => {
          faultReport.value = res;
          resolve(res);
        })
        .catch((error) => {
          console.error("获取新故障报告详情失败:", error);
          reject(error);
        });
    });
  }

  return {
    // 状态
    loading,
    faultReportList,
    total,
    selectedIds,
    faultReport,

    // 方法
    fetchFaultReportByCpuId,
  };
});

/**
 * 适用于 setup 之外的场景
 */
export function useFaultReportStoreHook() {
  return useFaultReportStore(store);
}
